<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/rights' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/rights' }">
        角色列表
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col>
        <el-button type='primary' style="margin: 20px 0">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 角色表格 -->
    <el-card>
      <el-table :data='rolesList' border stripe :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }">
        <!-- 展开列 -->
        <el-table-column type='expand'>
          <!-- 角色权限渲染 -->
          <template slot-scope="scope">
            <el-row :class="['bb', index1 ==0? 'bt':'', 'alc']" v-for="(item1, index1) in scope.row.children" :key='item1.id'>
              <!-- 渲染一级权限 -->
              <el-col :span='6'>
                <el-tag closable>{{item1.authName}}</el-tag>
                <i class='el-icon-caret-right'></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span='18'>
                <el-row :class="[index2==0? '': 'bt', 'alc']" v-for="(item2,index2) in item1.children" :key='item2.id'>
                  <!-- 渲染二级权限 -->
                  <el-col :span='6'>
                    <el-tag type='success' closable>
                      {{item2.authName}}
                    </el-tag>
                    <i class='el-icon-caret-right'></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span='18'>
                    <el-tag type='warning' closable v-for="item3 in item2.children" :key='item3.id' @close=removeRightsById(scope.row,item3.id)>
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type='index' label='#'></el-table-column>
        <el-table-column prop='roleName' label='角色名称'>
        </el-table-column>
        <el-table-column prop='roleDesc' label='角色描述'>
        </el-table-column>
        <el-table-column label='操作'>
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit-outline" size='mini'>
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size='mini'></el-button>
            <el-tooltip class="item" effect="light" content="分配权限" placement="top-start" :enterable='false'>
              <el-button type="warning" icon="el-icon-setting" size='mini' @click='rightsShow(scope.row)'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightVisible" width="60%" @close='rightsNone'>
      <!-- 通过树形控件展示权限 -->
      <el-tree :data="rightsList" :props="defaultProps" :default-checked-keys='checkedKeys' node-key="id" show-checkbox default-expand-all ref='rightsTree'></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      // 存放角色列表数据
      rolesList: [],
      // 控制权限对话框的显示隐藏
      rightVisible: false,
      // 权限数据
      rightsList: [],
      // 树形菜单渲染设置
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      // 树形菜单默认选中的选项
      checkedKeys: [],
      // 当前角色的id
      roleId: '',
    }
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data } = await this.$http.get('roles')
      if (data.meta.status != 200) return this.$message.error('获取角色列表失败')
      this.rolesList = data.data
    },
    // 删除tag标签渲染的权限
    async removeRightsById(role, rightId) {
      let isConfirm = await this.$confirm('确定删除该权限吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      if (!isConfirm) return this.$message.info('取消了删除权限操作')
      // 用户点击了确定
      const { data } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

      if (data.meta.status != 200) return this.$message.error('删除权限失败 !')

      // 重新获取数据会导致页面重新渲染
      // this.getRolesList()

      // 上面这种方式会重新请求服务器加载所有的数据 更新rolesList 而rolesList的更新会引起依赖该数据的视图更新 而依赖它的视图是整个表格 所以整个表格会刷新 展开的列也会收起 需要重新打开才能看到最新的数据

      // 我们希望只有role对应的权限部分发生重新渲染
      // 所以我们只对role.children进行重新赋值
      // 赋值的是服务器返回的最新的role对应的权限
      role.children = data.data
    },
    // 点击分配权限的弹窗
    async rightsShow(role) {
      // 保存一份roleId
      this.roleId = role.id
      // 获取所有子节点
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status != 200) return this.$message.error('获取权限列表失败')
      this.rightsList = data.data
      // 递归将所有id放入checkedKeys数组中
      this.getKeys(role)
      // 展示
      this.rightVisible = true
    },
    // 递归获取到所有选中的id
    getKeys(role) {
      // 没有子级
      if (!role.children) {
        return this.checkedKeys.push(role.id)
      }
      // 有子级
      role.children.forEach((item) => {
        // 递归
        this.getKeys(item)
      })
    },
    // 权限弹窗关闭时
    rightsNone() {
      // 清空权限树形菜单默认选中的选项
      this.checkedKeys = []
      // 关闭弹窗
      this.rightVisible = false
    },
    // 点击确定更新权限
    async updateRights() {
      // 合并选中和半选中状态的id
      let arrs = [
        ...this.$refs.rightsTree.getCheckedKeys(), 
        ...this.$refs.rightsTree.getHalfCheckedKeys()
      ]
      // 以 , 分割
      arrs = arrs.join(',')
      // 发起请求
      await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: arrs,
      })
      this.$message.success('权限分配成功')
      this.getRolesList()
      // 关闭弹窗
      this.rightVisible = false
    },
  },
  created() {
    this.getRolesList()
  },
}
</script>

<style lang="less">
.el-tag {
  margin: 8px;
}
.bt {
  border-top: 1px solid #eee;
}
.bb {
  border-bottom: 1px solid #eee;
}
.alc {
  display: flex;
  align-items: center;
}
</style>